package com.coder.widget.slidecard

import android.graphics.Canvas
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.sqrt

/**
 * 滑动回调
 *
 * @author yuhushuan
 * @date 2020/11/6 20:06
 */

class SlideCallback(private val listener: SlideListener) : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.UP
        or ItemTouchHelper.DOWN
        or ItemTouchHelper.LEFT
        or ItemTouchHelper.RIGHT) {

    interface SlideListener {
        fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int)
    }


    override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
        return false
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        listener.onSwiped(viewHolder, direction)
    }

    private fun getThreshold(recyclerView: RecyclerView): Float {
        return recyclerView.width * 0.4f
    }

    override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
        val maxDistance = getThreshold(recyclerView).toDouble()
        val distance = sqrt(dX * dX + dY * dY.toDouble())
        var fraction = distance / maxDistance
        if (fraction > 1) {
            fraction = 1.0
        }

        // 显示的个数
        val itemCount = recyclerView.childCount
        for (i in 0 until itemCount) {
            val view = recyclerView.getChildAt(i)
            val level = itemCount - i - 1
            if (level > 0) {
                if (level < CardConfig.MAX_DISPLAY_COUNT - 1) {
                    view.translationY = (CardConfig.TRANS_Y_GAP * level - fraction * CardConfig.TRANS_Y_GAP).toFloat()
                    view.scaleX = (1 - CardConfig.SCALE_GAP * level + fraction * CardConfig.SCALE_GAP).toFloat()
                    view.scaleY = (1 - CardConfig.SCALE_GAP * level + fraction * CardConfig.SCALE_GAP).toFloat()
                }
            }
        }
    }

    override fun getAnimationDuration(recyclerView: RecyclerView, animationType: Int, animateDx: Float, animateDy: Float): Long {
        return 200
    }

}